#include "point.h"
#include "linesegment.h"
#include "p2pm.h"

namespace CX = CxQML;
using namespace CX;

P2Pm::P2Pm()
{

}

P2Pm::P2Pm(const Point& point1, const Point& point2, const Point& point3, const Point& point4)
{
    insertLastPoint(point1);
    insertLastPoint(point2);
    insertLastPoint(point3);
    insertLastPoint(point4);
}

P2Pm::P2Pm(const Point& point1, const Point& point2)
{
    insertLastPoint(point1);
    insertLastPoint(Point(point2.x(), point1.y()));
    insertLastPoint(point2);
    insertLastPoint(Point(point1.x(), point2.y()));
}

P2Pm::P2Pm(const Point& point, double width, double height)
{
    insertLastPoint(point);
    insertLastPoint(Point(point.x()+width, point.y()));
    insertLastPoint(Point(point.x()+width, point.y()+height));
    insertLastPoint(Point(point.x(), point.y()+height));
}

P2Pm::~P2Pm()
{

}

P2Pm::operator QString()
{
    return QString("P2Pm(%1; %2; %3; %4)").
            arg(topSide(), rightSide(),
                bottomSide(), leftSide());
}

int P2Pm::necessaryPointsQuant() const
{
    return 4;
}


bool P2Pm::isClosed() const
{
    return true;
}

bool P2Pm::isValid() const
{
    if (!Figure::isValid())
        return false;

    return topSide().length() == bottomSide().length() &&
            leftSide().length() == rightSide().length() &&
            checkDiagonslsEquality();
}

double P2Pm::width() const
{
    return fabs(getMaxX() - getMinX());
}

double P2Pm::height() const
{
    return fabs(getMaxY() - getMinY());
}

bool P2Pm::checkDiagonslsEquality() const
{
    LineSegment diagonal1(topLeftPoint(), bottomRightPoint());
    LineSegment diagonal2(bottomLeftPoint(), topRightPoint());

    return (diagonal1.length() - diagonal2.length()) < DBL_EPSILON;
}

Point P2Pm::topLeftPoint() const
{
    return topSide().firstPoint();
}

Point P2Pm::topRightPoint() const
{
    return topSide().lastPoint();
}

Point P2Pm::bottomLeftPoint() const
{
    return bottomSide().lastPoint();
}

Point P2Pm::bottomRightPoint() const
{
    return bottomSide().firstPoint();
}

LineSegment P2Pm::topSide() const
{
    return getSide(0);
}

LineSegment P2Pm::rightSide() const
{
    return getSide(1);
}

LineSegment P2Pm::bottomSide() const
{
    return getSide(2);
}

LineSegment P2Pm::leftSide() const
{
    return getSide(3);
}

QString P2Pm::className() const
{
    return "P2Pm";
}
